﻿using AutoMapper;
using FlyingHat.Common.Global;
using FlyingHat.Common.Helper;
using FlyingHat.Model.Enums;
using FlyingHat.Model.Models;
using FlyingHat.Model.Models.Global;
using FlyingHat.Office.Import;
using FlyingHat.Service.IService;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using OfficeOpenXml;

namespace FlyingHat.Web.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class UserController : BaseController
    {
        // 说明：本项目设计 管理员是特殊的用户，管理员和用户只是操作权限和数据权限不同。
        // 目前用户的身份是 超级管理员、管理员、学生。
        // 如果有其他需求可以在用户Identity 枚举中增加身份。所以我们在写判断身份的时候要明确身份，而不能用模糊身份判断
        // 这样可以对后期有增加身份的时候不会对现有的系统造成影响

        // 在菜单上我们把管理员和用户区分开，他们的功能是不同的
        // 管理员具有管理性质，在项目起始阶段没有可管理的功能，所以管理员功能可以延迟实现

        private readonly ILogger<UserController> logger;
        private readonly IUserService userService;
        private readonly IExcelImporter excelImporter;
        private readonly IMapper mapper;
        public UserController(IUserService userService, IExcelImporter excelImporter, ILogger<UserController> logger, IMapper mapper)
        {
            this.userService = userService;
            this.excelImporter = excelImporter;
            this.logger = logger;
            this.mapper = mapper;
        }
        #region 管理员
        [HttpGet]
        public IActionResult Admin()
        {
            return View();
        }

        #endregion

        #region 学生用户
        [HttpGet]
        public IActionResult Student()
        {
            var userStatus = EnumHelper.EnumItems(typeof(UserStatus));
            userStatus.Insert(0, new EnumItem { Value = -1, Description1 = "请选择" });
            ViewBag.UserStatus = userStatus.Select(i => new SelectListItem
            {
                Text = i.Description1,
                Value = i.Value.ToString(),
            });
            return View();
        }
        [HttpGet]
        public async Task<IActionResult> StudentList(string? userName, int page, int limit, UserStatus? userStatus = null)
            => Json(await userService.StudentList(userName, userStatus, page, limit));

        [HttpGet]
        public IActionResult AddStudent() => View();

        [HttpPost]
        public async Task<IActionResult> AddOrUpdateStudent(UserModel user)
        {
            var res = await userService.AddOrUpdateStudent(user);
            return Json(res);
        }

        [HttpGet]
        public IActionResult SetStatus()
        {
            var userStatus = EnumHelper.EnumItems(typeof(UserStatus)).Where(i => i.Value != (int)UserStatus.Init).ToList();
            userStatus.Insert(0, new EnumItem { Value = -1, Description1 = "请选择" });
            ViewBag.UserStatus = userStatus.Select(i => new SelectListItem
            {
                Text = i.Description1,
                Value = i.Value.ToString(),
            });
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> SetStatus(string? reason, int? blockDay, UserStatus setUserStatus, List<long> ids)
        => Json(await userService.SetStatus(reason, blockDay, setUserStatus, ids));



        [HttpGet]
        public async Task<IActionResult> GetStudentTemplate()
        {
            var by = await excelImporter.GenerateTemplateBytes<Student>();
            var user = new Student()
            {
                UserName = "20201219",
                Gender = Gender.Male,
                Phone = "13512341234",
                RealName = "张三"
            };
            using var stream = new MemoryStream(by);
            using var package = new ExcelPackage(stream);
            var sheet = package.Workbook.Worksheets.FirstOrDefault();
            if (sheet != null)
            {
                sheet.Name = "学生数据";
                int rowIndex = 2;
                sheet.Cells[rowIndex, 1].Value = user.UserName;
                sheet.Cells[rowIndex, 2].Value = user.RealName;
                sheet.Cells[rowIndex, 3].Value = user.Phone;
                sheet.Cells[rowIndex, 4].Value = user.Gender.GetDescription();
                by = package.GetAsByteArray();
            }

            return File(by, GlobalConst.Xlsx, "学生用户导入模板.xlsx");
        }

        [HttpPost]
        public async Task<IActionResult> UploadStudent(IFormFile file)
        {
            try
            {
                using var stream = file.OpenReadStream();
                var result = await excelImporter.Import<Student>(stream);
                if (result == null)
                {
                    return Json(ReturnModel.Fail("文件解析失败"));
                }
                if (result.HasError)
                {
                    var error = result.RowErrors.Take(5);
                    return Json(ReturnModel.Fail(2, "数据错误", error));
                }
                var res = await userService.ImportStudent(result.Data.ToList());
                return Json(res);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return Json(ReturnModel.Fail("文件上传解析异常"));
            }
        }

        #endregion

        #region 公共方法

        [HttpPost]
        public async Task<IActionResult> ModifyPasword(List<long> ids, string password)
            => Json(await userService.ModifyPasword(ids, password));

        [HttpPost]
        public async Task<IActionResult> BatchRemoveStudent(List<long> ids)
            => Json(await userService.BatchRemoveStudent(ids));

        public IActionResult Import()
        {
            return View();
        }
        #endregion
    }
}
